package cn.tonyandmoney.voicenotes.notes.presenter

import android.content.Context
import android.text.TextUtils
import cn.tonyandmoney.voicenotes.R
import cn.tonyandmoney.voicenotes.notes.entity.TNote
import cn.tonyandmoney.voicenotes.notes.enums.OperationEnum
import cn.tonyandmoney.voicenotes.notes.filters.InputFilter
import cn.tonyandmoney.voicenotes.notes.filters.OperationFilter
import cn.tonyandmoney.voicenotes.notes.model.NoteModel
import cn.tonyandmoney.voicenotes.notes.model.OperationCallback
import com.github.promeg.pinyinhelper.Pinyin
import com.github.promeg.tinypinyin.lexicons.android.cncity.CnCityDict
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error
import org.jetbrains.anko.info

/**
 * 这个是笔记录入的界面的控制器
 * 必须要处理语音输入的任务解析
 */
class ReaderPresenter(mView: IReaderInterface, context: Context)
    : OperationCallback(mView, context), AnkoLogger {


    private var enable = false
    private val mNoteModel = NoteModel()

    fun init(context: Context) {
        Observable.create<Int> {
            addFilter(OperationFilter(this))
            addFilter(InputFilter(this))
            Pinyin.init(Pinyin.newConfig().with(CnCityDict.getInstance(context)))
            it.onNext(0);it.onComplete()
        }.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer { enable = true;mView.onEnable(enable) },
                        ErrorConsumer())
    }

    /**
     * 保存当前的笔记,
     *
     */
    fun saveNote() {
        AndroidSchedulers.mainThread().scheduleDirect { mView.showLoadingDialog(R.string.is_saving_please_wait) }
        mState.operation = OperationEnum.NONE
        Observable.create<String> {
            info("saveNote")
            val note = TNote()
            note.name = mView.getInputText(R.id.record_name)
            note.memo = mView.getInputText(R.id.record_memo)
            note.type = mView.getInputText(R.id.record_type)
            note.content = mView.getInputText(R.id.record_content)
            mNoteModel.addNote(note)
            val paths = saveRecord(note.name)
            paths.forEach {
                mNoteModel.addRecordNote(note.id, mNoteModel.addRecord(it))
            }
            it.onNext("success")
            it.onComplete()
        }.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    mView.saveResult(0, "保存成功。")
                }, {
                    error("保存失败->", it)
                    mView.saveResult(-1, "保存失败，请重试。")
                })
    }

    override fun operation(operation: OperationEnum, params: MutableMap<String, String>) {
        info("operation:  $operation")
        when (operation) {
            OperationEnum.INPUT_NAME -> {
                mState.operation = operation
                mView.onState(mState)
            }
            OperationEnum.INPUT_MEMO -> {
                mState.operation = operation
                mView.onState(mState)
            }
            OperationEnum.INPUT_CONTENT -> {
                mState.operation = operation
                val name = mView.getInputText(R.id.record_name)
                if (TextUtils.isEmpty(name)) {
                    //提示输入标签
                } else {
                    startRecord(Pinyin.toPinyin(name, ""))
                }
                mView.onState(mState)
            }
            OperationEnum.INPUT_TYPE -> {
                mState.operation = operation
                mView.onState(mState)
            }
            OperationEnum.CONFIRM -> {  //确定操作会根据当前的任务来执行的
                mState.operation = OperationEnum.NONE
                mView.hideState()
            }
            OperationEnum.CANCEL -> {    //取消当前的输入
                resetInput(mState.operation)
                mState.operation = OperationEnum.NONE
                mView.hideState()
            }
            OperationEnum.SAVE -> {
                saveNote()
                mView.hideState()
            }
            else -> {
            }
        }
    }

    /**
     * 取消的时候，清除之前的输入
     */
    private fun resetInput(operation: OperationEnum) {
        when (operation) {
            OperationEnum.INPUT_NAME -> mView.onName("")
            OperationEnum.INPUT_MEMO -> mView.onMemo("")
            OperationEnum.INPUT_CONTENT -> mView.onMemo("")
            OperationEnum.INPUT_TYPE -> mView.onType("")
            else -> {
            }
        }
    }

    fun onExit() = Unit

    /**
     * 错误事件处理
     */
    inner class ErrorConsumer : Consumer<Throwable> {
        override fun accept(t: Throwable?) {
            info("ErrorConsumer: $t")
        }
    }
}
